import os

mode = 'debug'
MCU = 'APM32'
PROJECT_NAME = ''

start_file = 'lib/Device/Geehy/APM32F10x/Source/gcc/startup_apm32f10x_hd.S'
link_script = 'lib/Device/Geehy/APM32F10x/Source/gcc/gcc_APM32F10xxB.ld'
# 宏定义
define = [
    'APM32F10X_HD'
]

# 源码路径
src_dir = [
    'src/',
    'thiryparty/RTT/',
    'lib/APM32F10x_StdPeriphDriver/src/'
]

# 头文件路径
inc_dir = [
'lib/CMSIS/Include', 
'lib/APM32F10x_StdPeriphDriver/inc',
'lib/Device/Geehy/APM32F10x/Include',
'thiryparty/RTT/'
]

# Lib库路径
lib_dir = []

# CC flag
cc_flags = [
    '-mcpu=cortex-m3',
    '-mthumb',
    '-O0',
    '-Wall',
    '-ffunction-sections',
    '-fdata-sections',
    '--specs=nano.specs',
    '-nostdlib'
]

# Link flag
link_flags = [
    '-mcpu=cortex-m3',
    '-mthumb',
    '-Wl,--gc-sections',
    '--specs=nano.specs',
    '-T',
]
link_flags.append(link_script)

# Import the necessary SCons tools
env = Environment(
    TOOLS=['gcc', 'g++', 'gnulink', 'ar'],
    CC='arm-none-eabi-gcc',
    CXX='arm-none-eabi-g++',
    AS='arm-none-eabi-as',
    AR='arm-none-eabi-ar',
    LINK='arm-none-eabi-gcc',
    OBJCOPY='arm-none-eabi-objcopy'
)

env.Decider('MD5-timestamp')

# Define the target architecture and optimization flags
env.Append(
    CCFLAGS = cc_flags,
    LINKFLAGS = link_flags,
    CPPDEFINES = define,
    CPPPATH = inc_dir,
    LIBPATH = lib_dir
)

# Add source files
src_files = []
src_files.append(start_file)
for dir in src_dir:
    src_files = src_files + Glob(dir + '*.c')
    src_files = src_files + Glob(dir + '*.cpp')

# Create the elf binary target
elf_target = env.Program(target='build/apm32_scons.elf', source=src_files)

# Create hex and bin output formats from the elf file
hex_target = env.Command('build/apm32_scons.hex', elf_target, '$OBJCOPY -O ihex $SOURCE $TARGET')
bin_target = env.Command('build/apm32_scons.bin', elf_target, '$OBJCOPY -O binary $SOURCE $TARGET')

# Default build target
Default(elf_target, hex_target, bin_target)